package com.lkm.app_ui.m.Imple.hsj522;

import com.lkm.app_ui.AppConst;
import com.lkm.app_ui.RunTimeData;
import com.lkm.app_ui.entity.SteelyardExtData;
import com.lkm.app_ui.help.LogHelp;
import com.lkm.app_ui.help.TaskHelp;
import com.lkm.app_ui.m.Imple.fun.FunModuleDelegate;
import com.lkm.app_ui.m.nfc.NFC_Module;
import com.lkm.app_ui.m.nfc.OnNFCModuleStateEvent;
import com.lkm.app_ui.m.push.PushModule;
import com.lkm.app_ui.ui.DelegateInitFragment;
import com.lkm.frame.P;
import com.lkm.frame.otto.LinkBus;
import com.lkm.frame.otto.LinkBusEventFlag;
import com.lkm.frame.otto.Observer;
import com.lkm.frame.otto.ObserverAutoNext;
import com.lkm.frame.task.ProgressData;
import com.lkm.frame.task2.BackCallAdapter;
import com.lkm.frame.task2.Task;
import com.lkm.frame.task2.TaskManager;
import com.lkm.hardware_connect.ConnectTaskResult;
import com.lkm.javatool.NumberHelp;
import com.lkm.javatool.StringHelp;
import com.lkm.javatool.lang.RunnablePR;
import com.lkm.market2_0.AppDataCache;
import com.lkm.market2_0.entity.NfcCarInfo;
import com.lkm.market2_0.entity.OrganizationInfo;
import com.lkm.market2_0.entity.PayTo;
import com.lkm.market2_0.entity.SteelyardInfo;
import com.lkm.market2_0.m.steelyarddata.OnSteelardInfoLoadEvent;
import com.lkm.market2_0.netapi.Api;




public class NFC_ModuleHSJ522Module implements NFC_Module {

    private CardCircuitComSe cardCircuitCom;

    private TaskManager mTaskManager;

    public NFC_ModuleHSJ522Module() {

        this.cardCircuitCom = new CardCircuitComSe();


        mTaskManager = AppConst.getTaskManager2();

        connect(true);

        
        LinkBus.registerReceiver(new ObserverAutoNext<OnNFCModuleStateEvent>() {
            @Override
            public void onReceiver(OnNFCModuleStateEvent data) {
                if(data.isConnecSuccess()){
                    if (RunTimeData.steelyardInfo == null) return;
                    if(isolsSAJ(RunTimeData.steelyardInfo)){
                        loadKey(new byte[]{0x02, 0x00, 0x00, 0x00, 0x01, 0x03});
                        P.d("=== 食安检刷卡");
                    }else {
                        NfcCarInfo pos = RunTimeData.steelyardInfo.getPos();
                        if (pos != null) {
                            
                            if(!StringHelp.isEmpty(pos.key))
                            loadKey(LogHelp.toBytes(pos.key));
                        }

                    }
                }

            }

            @Override
            public Class getBusEventClass() {
                return OnNFCModuleStateEvent.class;
            }
        });

        
        LinkBus.registerReceiver(new ObserverAutoNext<OnSteelardInfoLoadEvent>() {
            @Override
            public Class getBusEventClass() {
                return OnSteelardInfoLoadEvent.class;
            }
            private String oldKey = null;
            @Override
            public void onReceiver(OnSteelardInfoLoadEvent data) {
                SteelyardInfo steelyardInfo = data.getSteelyardInfo();
                NfcCarInfo pos = steelyardInfo == null ? null : steelyardInfo.getPos();
                if(steelyardInfo !=null && isolsSAJ(data.getSteelyardInfo())){
                    loadKey(new byte[]{0x02, 0x00, 0x00, 0x00, 0x01, 0x03});
                    P.d("=== 食安检刷卡");
                }else
                if (pos != null && !StringHelp.isEmpty(pos.key)) {
                    if (!pos.key.equals(oldKey)) {
                        loadKey(LogHelp.toBytes(oldKey = pos.key));
                    }
                }
            }
        });

        startLoopCardInOutTask();
    }


    private boolean isolsSAJ(SteelyardInfo steelyardInfo){
        return !Api.isASTApi() && steelyardInfo.getPos() == null;
    }

    @Override
    public Task<Void, String, ConnectTaskResult> connect(boolean isFailReconnect) {
        return cardCircuitCom.connect(isFailReconnect);
    }

    @Override
    public void disConnect() {
        cardCircuitCom.disConnect();
    }

    @Override
    public boolean isConnect() {
        return cardCircuitCom.getConnectStater().isConnect();
    }
    private RunnablePR<String, Void> onCardInRun;

    public void setOnCardInRun(RunnablePR<String, Void> onCardInRun) {
        this.onCardInRun = onCardInRun;
    }
    public void startLoopCardInOutTask() {

        TaskHelp.cancelById("startLoopCardInOutTask" );

        LoopCardInOutTask task = new LoopCardInOutTask("startLoopCardInOutTask" , this);
        task.action();
        task.addBackCall(new BackCallAdapter<String, Void>() {
            @Override
            public void onProgresing(Task<?, String, Void> task, ProgressData<String> progressData) {
                super.onProgresing(task, progressData);
                if (onCardInRun != null && progressData != null && progressData.getData() != null) {
                    onCardInRun.run(progressData.getData());
                }

            }
        });
        task.execTask();
    }
    
    @Override
    public Task tryReadCardNum() {

        SendGetCardNumCMDTask sendGetCardNumCMDTask = new SendGetCardNumCMDTask(cardCircuitCom);





//                    listener.onFinderCard(r == null ? null : (String) r.getData());



        sendGetCardNumCMDTask.setParam(null);
        sendGetCardNumCMDTask.action();
        return sendGetCardNumCMDTask;
    }
    
    @Override
    public Task tryReadBolck(int sectorIndex,int blockIndex) {

        SendReadBlockTask sendReadBlockTask = new SendReadBlockTask(cardCircuitCom,sectorIndex, blockIndex);
        sendReadBlockTask.setParam(null);
        sendReadBlockTask.action();
        return sendReadBlockTask;
    }
    private void rewaitReadVipInfo(){
        TaskHelp.cancelById(WaitVipidTaskId);
    }
    private static String WaitVipidTaskId = "WaitVipidTask";
    @Override
    public Task waitReadVipInfo(){
        Task task = TaskHelp.getTask(WaitVipidTaskId);
        if (task != null && task.getIsContinue()) return  task;

        
        if (RunTimeData.steelyardInfo == null) return null;

        if(isolsSAJ(RunTimeData.steelyardInfo)){
            
            P.d("=== 食安检刷卡get");
            task = new WaitVipInfoForBlockTask(WaitVipidTaskId, this, false, 1, 0);
        }else {
            NfcCarInfo pos = RunTimeData.steelyardInfo == null ? null :  RunTimeData.steelyardInfo.getPos();
            if (pos == null) return null;

            if(pos.isBlock()){
                task = new WaitVipInfoForBlockTask(WaitVipidTaskId, this, pos.isCardNo(), pos.sectorIndex, pos.blockIndex);
            }else  if(pos.isCardNo()) {
                task = new WaitVipInfoForNoTask(WaitVipidTaskId, this);
            }
        }

        if (task == null) return task;
        task.action();
        task.execTask();
        return task;
    }


//        WatchCardBlockTask watchCardBlockTask = TaskHelp.getTask(WatchCardBlockTask.getTaskId());











    

    @Override
    public void loadKey(byte [] key) {
        SendLoadKeyTask sendCheckPassCMDTask = new SendLoadKeyTask( cardCircuitCom,key);
        sendCheckPassCMDTask.setParam(null);
        sendCheckPassCMDTask.action();
        sendCheckPassCMDTask.execTask();
    }


    private void test(){


//        AppConst.getModuleManager().getModule(NFC_Module.class, new RunnablePR<Boolean, Void>() {



//                NFC_Module nfc_module = AppConst.getModuleManager().loadModule(NFC_Module.class);



//                new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {








////                                new Handler(Looper.getMainLooper()).post(new Runnable() {


////                                        ViewUIHelp.showTipsLong(BaseFragmentActivity.getLastActivity(),carNum);


////                                System.out.println("====读到卡号 "+carNum);








    }


}
